package com.woniu.auth;

import com.woniu.dao.UsersMapper;
import com.woniu.domain.Users;
import com.woniu.domain.UsersExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


@Component
public class UserDetailService implements UserDetailsService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        UsersExample example = new UsersExample();
        UsersExample.Criteria criteria = example.createCriteria();
        criteria.andUserNameEqualTo(name);
        List<Users> users = usersMapper.selectByExample(example);
        if (users.size() == 0) {
            throw new UsernameNotFoundException("该用户不存在");
        }else{

            List<GrantedAuthority> granteds = new ArrayList<>();

            Users users1 = users.get(0);
            return new User(users1.getUserName(), passwordEncoder.encode(users1.getUserPwd()), granteds);
        }

    }
}
